package com.cz.datafetcher.config;

import com.cz.datafetcher.common.CronUtils;
import com.cz.datafetcher.dao.SuperMapper;
import com.cz.datafetcher.entity.FetchDevices;
import com.cz.datafetcher.service.FetchDataService;
import com.cz.datafetcher.service.FetchDevicesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@EnableScheduling
@Configuration
@Slf4j
public class Scheduler implements SchedulingConfigurer {
    @Autowired
    SuperMapper superMapper;
    @Autowired
    FetchDevicesService fetchDevicesService;
    @Autowired
    FetchDataService fetchDataService;
    @Value("${task.enable}")
    boolean enable;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        if(!enable) return;
        List<FetchDevices> list = fetchDevicesService.list();
        for (FetchDevices fetchDevices : list) {
            registerFetchDevicesTask(scheduledTaskRegistrar,fetchDevices);
        }
    }

    private void registerFetchDevicesTask(ScheduledTaskRegistrar scheduledTaskRegistrar, FetchDevices fetchDevices) {
        scheduledTaskRegistrar.addTriggerTask(()->{
            //fix time
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.MINUTE,0);
            calendar.set(Calendar.SECOND,0);
            calendar.set(Calendar.MILLISECOND,0);
            calendar.add(Calendar.SECOND,-fetchDevices.getPeriod());
            Date end=calendar.getTime();
            Calendar beginc = Calendar.getInstance();
            beginc.set(Calendar.MINUTE,0);
            beginc.set(Calendar.SECOND,0);
            beginc.set(Calendar.MILLISECOND,0);
            beginc.add(Calendar.SECOND,-fetchDevices.getPeriod() * 2);
            Date begin=beginc.getTime();

            //log.info("{} to {}", begin.getTime(),end.getTime());
            fetchDataService.Fetch(fetchDevices.getId().toString(),begin,end,true );
        },triggerContext -> {
            Integer period = fetchDevices.getPeriod();
            String cron=ConvertPeriod2Cron(period);
            return new CronTrigger(cron).nextExecutionTime(triggerContext);
        });
    }

    private String ConvertPeriod2Cron(Integer period) {
        //return "0/1 * * * * ?";
        return CronUtils.ConvertSeconds2Cron(period);
    }


}
